var express = require("express");
var router = express.Router();
var constants = require("../utils/constants");
const { checkAuth,checkField } = require("../utils/utils");
const { ohana } = require("ohana-node-orm");
const tableName = "JIANGDU_ALL_SERVICES";
const logtableName = "SAP_JIANGDU_ALL_LOGS";
// var moment = require("moment");

let log = require("cf-nodejs-logging-support");
log.setLoggingLevel("info");
var moment = require('moment')


router.post("/log",function(req,res,next){
    const {data} = req.body;
    // console.log(req.connection.remoteAddress)
    // if()
    data.IP=req.connection.remoteAddress;
    if(!data||!checkField(["DEVICE","TYPE"],data))
    {
    res.status(400).send({message:"至少需要 IP ，DEVICE ， TYPE 字段"});
    return;
    }
    data.CREATED_AT=moment().format("YYYY-MM-DD hh:mm:ss");
    insertLogs(data).then(result=>{
        if(result>0)
        {
            res.sendStatus(200)
        }else{
            res.sendStatus(400)
        }
    }).catch(err=>{
        res.status(500).send({error:err,message:"请检查字段"})
    })
});

async function insertLogs(data){
    const sqlConn = new ohana(logtableName);
    var result= await sqlConn.insert(data);
    return result;
}


router.put("/switchStatus", function (req, res, next) {
    const userNew = checkAuth(req.user, constants.ADMINAUTH);
    if (!userNew.authCheck) {
        /* #swagger.responses[403] = {
                description: '缺少权限'
                        } */
        res.sendStatus(403);
        return;
    }
    const { data } = req.body;
    changeStatusByType(data).then(result => {
        console.log(result);
        if (result > 0) { res.sendStatus(200) }
        else {
            res.sendStatus(400);
        }
    })
})
async function changeStatusByType(data) {
    const sqlConn = new ohana(tableName);
    var result = "";
    var table, column = ""
    switch (data.type) {
        case "FI":
            table = constants.FINTABLE;
            column = "FIN_ID";
            break;
        case "TA":
            table = constants.TALENTTABLE;
            column = "TALENT_ID";
            break;
        case "AS":
            table = constants.ASSETTABLE;
            column = "ASSET_ID";
            break;
        case "TE":
            table = constants.TECHTABLE;
            column = "TECH_ID";
            break;
        default:
            break;
    }
    var range = '';
    if (data.numberRange.length > 0) {
        data.numberRange.map((one, index) => {
            range += "'" + one + "'";
            if (index != data.numberRange.length - 1) {
                range += ","
            }
        })
    } else {
        return 0;
    }

    result = await sqlConn.raw("update " + table + " set STATUS = '" + data.STATUS + "' where " + column + " in (" + range + ")");
    result = await sqlConn.raw("update " + table + " set UPDATED_AT = '" + moment().format("YYYY-MM-DD hh:mm:ss") + "' where " + column + " in (" + range + ")");
    return result;
}

router.put("/setVIP", function (req, res, next) {
    const userNew = checkAuth(req.user, constants.ADMINAUTH);
    if (!userNew.authCheck) {
        /* #swagger.responses[403] = {
                description: '缺少权限'
                        } */
        res.sendStatus(403);
        return;
    }
    const { data } = req.body;
    setGlobal(data).then(result => {
        console.log(result);
        if (result > 0) { res.sendStatus(200) }
        else {
            res.sendStatus(400);
        }
    })


})
async function setGlobal(data) {
    const sqlConn = new ohana(tableName);
    var result = "";
    console.log(data)
    result = await sqlConn.raw("update GLOBAL_PARAMETER set " + data.VIP + " = '" + data.vipsetting + "'");
    return result;
}



router.get("/getGlobalParameter", function (req, res, next) {
    const userNew = checkAuth(req.user, constants.ADMINAUTH);
    if (!userNew.authCheck) {
        /* #swagger.responses[403] = {
                description: '缺少权限'
                        } */
        res.sendStatus(403);
        return;
    }
    getGlobalParam().then(result => {
        res.send(result);
    })
})

async function getGlobalParam() {
    const sqlConn = new ohana(tableName);
    sqlText = "select * from GLOBAL_PARAMETER";
    var result = await sqlConn.raw(sqlText);
    return result[0].GLOBAL_PARAMETER;
}
router.get("/", function (req, res, next) {
    // #swagger.tags = ['审批流程']
    // #swagger.summary = '审批流程'
    // #swagger.description = "获取不同状态的设备，金融，只有管理员能用"
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    /* #swagger.parameters['status'] = {
          description: "inprocess",
          required: false,
  } */
    const userNew = checkAuth(req.user, constants.ADMINAUTH);
    if (!userNew.authCheck) {
        /* #swagger.responses[403] = {
                description: '缺少权限'
                        } */
        res.sendStatus(403);
        return;
    }
    const { status } = req.query;
    if (!status) {
        /* #swagger.responses[400] = {
                description: '缺少状态'
                        } */
        res.status(400).send({ message: "缺少status参数" });
    }
    const sqlConn = new ohana(tableName);
    sqlText = "select * from " + tableName + " where STATUS = '" + status + "'";
    sqlConn
        .raw(sqlText)
        .then((result) => {
            res.send(result);
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

router.get("/allService", function (req, res, next) {
    // #swagger.tags = ['ALL SERVICE']
    // #swagger.summary = '所有服务'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    // const userNew = checkAuth(req.user, constants.ADMINAUTH);
    // if (!userNew.authCheck) {
    //     res.sendStatus(403);
    //     return;
    // }
    const sqlConn = new ohana(tableName);
    sqlText =
        'select * from "JIANGDU_ALL_SERVICES" ORDER BY UPDATED_AT DESC LIMIT 10';
    sqlConn
        .raw(sqlText)
        .then((result) => {
            res.status(200).send(result);
        })
        .catch((err) => {
            res.status(500).send(err);
        });
});
module.exports = router;
